var tableIns;
var searchParam = null;//用于存表单查询的条件参数
layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    //日期
    function getNowFormatDate() {
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = "'"+date.getFullYear() + "-" + month + "-" + strDate
            + " " + hours + ":" + minutes + ":" + seconds+"'";
        return currentdate;
    }
    var getNowFormatDate = getNowFormatDate();
    var dateMin = laydate.render({
        elem: '#regDateMin',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,//设置一个默认最大值
        done: function (value, dates) {
            dateMax.config.min ={
                year:dates.year,
                month:dates.month-1, //关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            };
        }
    });
    var dateMax = laydate.render({
        elem: '#regDateMax',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,
        done:function (value,dates) {
            dateMin.config.max={
                year:dates.year,
                month:dates.month-1,//关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            }
        }
    });
    var form = layui.form,
         layer=layui.layer;
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    tableIns = table.render({
        id:"id",
        elem: '#speakingPackageTable',
        url : baseUrl + '/flowConfig/querySpeakingPackagePage',
        cellMinWidth : 95,
        page : true,
        request: {
            pageName: 'page' //页码的参数名称，默认：page
            ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            ,statusCode: 1 //成功的状态码，默认：0
            ,msgName: 'msg' //状态信息的字段名称，默认：msg
            ,countName: 'total' //数据总数的字段名称，默认：count
            ,dataName: 'records' //数据列表的字段名称，默认：data
        }, loading: true
        ,where:{
            "doSearch":$("#doSearch").val()
        }
        ,page: {
            id:"id",
            limit: 10
            ,limits: [10, 20, 30, 40, 50]
            ,curr: 1
            ,groups: 5
            ,theme: '#5FB878'
            ,first: '首页'
            ,last: '尾页'
            ,prev: '<em><i class="layui-icon">&#xe603;</i></em>'
            ,next: '<em><i class="layui-icon">&#xe602;</i></em>'
            ,layout: [ 'prev', 'page', 'next', 'skip','count']
        },
        cols : [[
            /*{type: "checkbox", fixed:"left", width:50 },*/
            {field: 'packageName', title: '话术名称', width:'15%', minWidth:120},
            // {field: 'packageType', title: '类型', align:'center', width:'10%', minWidth:100},
            {field: 'selIndutryTypeName', title: '已选的行业话术包', align:'center', width:'15%', minWidth:120},
            {field: 'createUserName', title: '创建人', align:'center', width:'10%', minWidth:100},
            {field: 'createTime', title: '创建时间', align:'center', width:'15%', minWidth:110},
            {field: 'checkStatus', title: '审核状态', align:'center', width:'15%', minWidth:110},
            {title: '操作', templet:'#techniqueListBar',fixed:"right",width:'30%',align:"center", minWidth:150}
        ]],done: function(res, curr, count){
            intTableColorChange();
        }
        ,text: {
            // none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
            none: "false"==$("#doSearch").val()?'':'暂无相关数据'
        }
    });


    //列表操作
    table.on('tool(speakingPackageTable)', function(obj){
        var layEvent = obj.event,
            param = obj.data;
        if(layEvent === 'edit'){ //编辑
            addSpeakingSkillDetail(false,param.id);
        } else if(layEvent === 'del'){ //删除
            layer.confirm('您确定删除此话术包？',{icon:3, title:'提示信息'},function(index){
                var load = layer.msg('执行中，请稍候',{icon: 16,time:false,shade:0.8});
                $.ajax({
                    type: "POST",
                    url:  baseUrl+'/flowConfig/delSpeakingPackage?id='+param.id,
                    dataType: 'json',
                    success: function (data) {
                        layer.close(load);
                        if(data.code<=0){
                            layer.msg(data.msg);
                            layer.close(index);
                        }else{
                            reloadTable();
                            layer.close(index);
                        }
                    },
                    error: function () {
                        layer.close(load);
                        layer.msg("保存失败");
                        layer.close(index);
                    }
                });
            });
        } else if(layEvent === 'setflow'){ //设置流程
            /*http://localhost:8880/linkcall/flowConfig/speakingPackageConfig
            content : [baseUrl+"/flowConfig/flowSetting?flowType=main&packageId="+param.id],*/
            var setFlowWin = layer.open({
                title : false,
                type : 2,
                content : [baseUrl+"/flowConfig/speakingPackageConfig?packageId="+param.id],
                resize:true,
                maxmin:false,
                isOutAnim:true,
                scrollbar:true,
                area : ['86%', '95%'],
                success : function(layero, index){
                    setTimeout(function(){
                        layer.tips('点击此处返回流程列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            });
            setTimeout(function(){
                layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            },500);
            layui.layer.full(setFlowWin);
            // layui.layer.full(setFlowWin);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            /*$(window).on("resize",function(){
                layui.layer.full(setFlowWin);
            })*/
        } /*else if(layEvent === 'setMultiWheelFlow'){ //设置多轮会话
            var setMultiWheelFlowWin = layer.open({
                title : "多轮会话配置",
                type : 2,
                content : [baseUrl+"/flowConfig/flowSetting?flowType=multiWheel&packageId="+param.id],
                resize:true,
                maxmin:false,
                isOutAnim:true,
                scrollbar:true,
                success : function(layero, index){
                    setTimeout(function(){
                        layer.tips('点击此处返回流程列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            });
            layui.layer.full(setMultiWheelFlowWin);
        }*/
        else if(layEvent == 'check'){
            var status = "Y";
            var tipMsg = "您确定审核通过此话术包，通过后，话术包可以被绑定到call客包?";
            if(param.checkStatus == '已审核'){
                tipMsg = "此话术包已审核通过，您确定进行反审核，禁止被绑定到call客包?";
                status = 'N';
            }
            layer.confirm(tipMsg,{icon:3, title:'提示信息'},function(index){
                var load = layer.msg('执行中，请稍候',{icon: 16,time:false,shade:0.8});
                $.ajax({
                    type: "POST",
                    url:  baseUrl+'/flowConfig/checkSpeakingPackage?id='+param.id+'&checkStatus='+status,
                    dataType: 'json',
                    success: function (data) {
                        layer.close(load);
                        if(data.code<=0){
                            layer.msg(data.msg);
                            layer.close(index);
                        }else{
                            reloadTable();
                            layer.close(index);
                        }
                    },
                    error: function () {
                        layer.close(load);
                        layer.msg("保存失败");
                        layer.close(index);
                    }
                });
            });
        }
    });


    // 提交查询条件表单
    form.on('submit(query)', function(data){
        searchParam = data.field;
        reloadTable();
    });

    //添加话术
    function addSpeakingSkillDetail(edit,id){
        var params = "?id="+id;
        currentIndex = layer.open({
            title : "新增话术",
            type : 2,
            content : [baseUrl+"/flowConfig/addSpeakingPackage"+params],
            resize:true,
            maxmin:false,
            isOutAnim:true,
            scrollbar:true,
            area : ['570px','360px'],
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                button.click();
                reloadTable();
            }
            , btn2: function (index, layero) {
                layer.close(index);
            }
        });
    }
    $("#add_btn").click(function(){
        addSpeakingSkillDetail(false,'0');
    });

    //选中行时，高亮显示
    function intTableColorChange(){
        $(".layui-table-body tr").click(function(e){
            $(".layui-table-body  tr ").css("background","");
            $(this).css("background","#e6e6e6");
        });
    }


    //table加载后 执行的方法
    function loadTableByDone(res, curr, count) {
        //如果是异步请求数据方式，res即为你接口返回的信息。
        //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
        console.log(res);
        //得到当前页码
        console.log(curr);
        //得到数据总量
        console.log(count);
        intTableColorChange();
        LayUIDataTable.SetJqueryObj($);// 第一步：设置jQuery对象
        LayUIDataTable.HideField('id');// 隐藏列-单列模式
        var currentRowDataList = LayUIDataTable.ParseDataTable(function (index, currentData, rowData) {
            console.log("当前页数据条数:" + currentRowDataList.length);
            console.log("当前行索引：" + index);
            console.log("触发的当前行单元格：" + currentData);
            console.log("当前行数据：" + JSON.stringify(rowData));
            console.log(rowData.id);
        });
    }
});


//重新加载table的数据
function reloadTable() {
    var load = layer.load();
    var whereParam = {};
    if(searchParam!=null){
        whereParam = searchParam;
    }
    //点击查询时=== 执行查询操作为true
    whereParam["doSearch"] = "true";
    tableIns.reload({
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: whereParam
    });
    layer.close(load);
}


/*
window.addEventListener('message', function(e)
{
    console.log('listen.....');
    var data = JSON.parse(e.data);
    if(data.key =="postUserMsg" && data.type == "SET"){
        console.log("Receive user info:"+data.value);//userId, roleId, userName,userNo,canSearchAll
        var postUserData = JSON.parse(data.value);
        if(postUserData){
            $("#createUserId").val(postUserData.userId);
            $("#canSearchAll").val(postUserData.canSearchAll);
            $("#query").click();
        }
    }
}, false);*/
